package top.datacluster.basic.algorithm.leetcode.tree;

import top.datacluster.basic.algorithm.leetcode.TreeNode;

public class LeetCode1596 {

    public boolean isBalanced(TreeNode root) {
        if (Math.abs(getTreeHeight(root.left) - getTreeHeight(root.right)) <= 1){
            if (root.left != null){
                if (!isBalanced(root.left)){
                    return false;
                }
            }
            if (root.right != null){
                if (!isBalanced(root.right)){
                    return false;
                }
            }
            return true;

        }else{
            return false;
        }

    }

    public int getTreeHeight(TreeNode root){
        if (root == null){
            return 0;
        }
        if (root.left == null && root.right == null){
            return 1;
        }else{
            return Math.max(getTreeHeight(root.left), getTreeHeight(root.right)) + 1;
        }

    }

    public static void main(String[] args) {
        TreeNode node = new TreeNode(10);
        TreeNode node1 = new TreeNode(12);
        TreeNode node2 = new TreeNode(6);
        TreeNode node3 = new TreeNode(8);
        TreeNode node4 = new TreeNode(3);
        TreeNode node5 = new TreeNode(11);
        node.left = node1;
        node.right = node2;
        node1.left = node3;
        node1.right = node4;
        node2.left = node5;
        System.out.println(new LeetCode1596().isBalanced(node));
    }
}
